package com.lemon.cloud.websocket.distribute;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.lemon.cloud.websocket.message.MessageDO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.nio.charset.StandardCharsets;

@AllArgsConstructor
@Slf4j
public class RedisWebsocketMessageListener implements MessageListener, MessageSender {

    private final RedisTemplate<String,String> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern){
        log.info("redis channel Listener message send {}", message);
        byte[] channelBytes = message.getChannel();
        RedisSerializer<String> stringSerializer = this.redisTemplate.getStringSerializer();
        String channel = stringSerializer.deserialize(channelBytes);
        if (MessageDistributor.DISTRIBUTOR_KEY.equals(channel)) {
            byte[] bodyBytes = message.getBody();
            try {
                String str = StrUtil.str(bodyBytes, StandardCharsets.UTF_8);
                if (JSONUtil.isTypeJSON(str)){
                    MessageDO messageDO = JSONUtil.parseObj(str).toBean(MessageDO.class);
                    this.doSend(messageDO);
                }
            } catch (Exception e) {
                log.error("distributor_key listener error,{},{}",channel,bodyBytes);
            }
        }
    }
}
